<template>
  <m-container class="inventory">
    <in-work-scan :palletCode="palletCode" @change="handleChange" scan />
  </m-container>
</template>

<script>
import { router } from '@/router'
import { imsStockInWorkList, getWorkOrder } from '@/api/modules/in-work'
import { getDicts } from '@/api/modules/dict'

export default {
  data() {
    return {
      dictMap: {},
      palletCode: '',
    }
  },
  async onLoad(options) {
    const { map } = await getDicts('ims_order_source_type')
    this.dictMap = {
      map,
    }

    options.palletCode && this.fetchData(options.palletCode)
  },
  methods: {
    async handleChange(barcode) {
      if (this.$Router.currentRoute.name !== 'ScanSearch') {
        return
      }

      if (barcode.startsWith('WMS-P-')) {
        this.palletCode = barcode
        this.fetchData(barcode)
      } else {
        uni.showToast({
          title: '请扫描正确的托盘码',
          icon: 'none',
        })
      }
    },
    async fetchData(palletCode) {
      const { rows } = await imsStockInWorkList({
        deliveryType: 1,
        palletCode,
      })
      if (rows.length === 0) {
        uni.showToast({
          title: '暂无数据',
          icon: 'none',
        })
        return
      }

      const inOrderId = rows[0].inOrderId
      const { data } = await getWorkOrder(inOrderId)
      this.$store.commit('inWork/setInfo', data)
      router.replace({
        name: 'StartIn',
        params: {
          inOrderId,
          type: 'systemInWork',
          api: 'default',
          status: 2,
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
